<template>
  <el-form
    ref="formRef"
    label-position="right"
    label-width="100px"
    :model="formData"
    :rules="formRules"
  >
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="formData.name" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="formData.code" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="formData.manager" placeholder="请选择负责人">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="formData.introduce" />
    </el-form-item>
    <el-form-item label-width="40%">
      <el-button>取消</el-button>
      <el-button type="primary" @click="doSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { deptAdd, deptSimple, getINfoById, editDept } from '@/api/department'
export default {
  props: {
    pid: {
      required: true,
      type: String
    },
    isEdit: {
      required: true,
      type: Boolean
    }
  },
  // 0.数据
  data() {
    return {
      // 0.1表单的数据
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 0.2负责人列表
      list: [],
      // 0.3表单校验
      formRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 1.created
  created() {
    // 1.1调用获取部门负责人
    this.getList()
    if (this.isEdit) {
      // 1.2 获取当前点击的信息
      this.getInfo(this.pid)
    }
  },
  // 2.方法
  methods: {
    // 2.1获取部门负责人列表
    async getList() {
      const res = await deptSimple()
      this.list = res.data
    },
    // 2.2确定按钮
    async doSubmit() {
      this.isEdit ? this.hEdit() : this.hAdd()
    },
    // 2.3获取当前点击的信息
    async getInfo(pid) {
      const res = await getINfoById(pid)
      this.formData = res.data
    },
    // 2.4新增的请求
    async hAdd() {
      // 发送请求
      await deptAdd({ ...this.formData, pid: this.pid })
      // 添加成功,通知父组件刷新列表,关闭弹窗
      this.$message.success('添加成功')
      this.$emit('hClose')
    },
    // 2.5编辑的请求
    async hEdit() {
      await editDept(this.formData)
      this.$message.success('编辑成功')
      this.$emit('hClose')
    }
  }
}
</script>

<style>

</style>
